<?php

namespace app\home\controller;

use think\Controller;
use think\Request;

class Good extends Base
{
   public function list(){
      $this->view->engine->layout(false);
      
      $id = input('id');
      // dump($id);
      $list = \app\common\model\Goods::where("cate_id",$id)->paginate(10);
      
      $category_state = \app\common\model\Category::find($id);
      return view('list',['goodslist'=>$list,'category_list'=>$category_state]); 
      
   }
   // 详情页
   function detail(){
      $this->view->engine->layout(false);
      // 获取参数
      $id = input('id');
      // 详情页面展示
      $detaildata = \app\common\model\Goods::find($id);
      // $data = \app\common\model\Goods::find($id);
      $detaildata['goods_attr'] =json_decode($detaildata['goods_attr'],true);
      // dump($detaildata); 
      // 查询相册
      $goodsImages = \app\common\model\GoodsImages::where('goods_id',$id)->find();
      // dump($goodsImages);
      
      // 查询商品规格
      $goodSpec = \app\common\model\SpecGoods::where('goods_id',$id)->select();
      // dump($specGoods);
      // 取出所有规则相关的id值
      // array_column($goodSpec->toArray(),'value_ids')   取出$goodSpec中的value_ids字段
      // implode('_',array_column($goodSpec->toArray(),'value_ids')) 将value_ids字段用'_'拼接
      // explode('_',implode('_',array_column($goodSpec->toArray(),'value_ids'))) 将value_ids字段用'_分割'
      // array_unique(explode() 取数组中的唯一元素
      $goodSpecId = array_unique(explode('_',implode('_',array_column($goodSpec->toArray(),'value_ids'))));
      // 根据规格id查询规格信息
      $goodSpec_info =\app\common\model\Spec::where('id','in',$goodSpecId)->select();
      // 转换数据格式，方便页面展示
      $res = [];
      foreach($goodSpec_info as $v){
         $res[$v['type_id']] = [
            'type_id'=>$v['type_id'],
            'spce_value'=>[]
         ];
      }
      foreach($goodSpec_info as $v){
         $res[$v['type_id']]['spce_value'][]=$v;
      }
      // dump($res);
      dump($goodSpec);
      $values_id_map=[];
      foreach($goodSpec as $v){
         $values_id_map[$v['value_ids']]=[
            'id'=>$v['id'],
            'price'=>$v['price']
         ];
      }
      // 要在js中使用关联素组$value_id_map 要将数据转换成json格式
      $values_id_map = json_encode($values_id_map);
      // dump($values_id_map);
      // dump($res);
      // return view('detail',['detaildata'=>$detaildata,'goodsImages'=>$goodsImages,'goodSpec'=>$res,'values_id_map'=>$values_id_map]);
   }
}
